package com.gutsyzhan.bilibili.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gutsyzhan.bilibili.constant.UserConstant;
import com.gutsyzhan.bilibili.constant.UserMomentsConstant;
import com.gutsyzhan.bilibili.dao.UserMomentsDao;
import com.gutsyzhan.bilibili.domain.UserMoments;
import com.gutsyzhan.bilibili.service.UserMomentsService;
import com.gutsyzhan.bilibili.util.RocketMQUtil;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class UserMomentsServiceImpl implements UserMomentsService {
    @Resource
    private UserMomentsDao userMomentsDao;

    @Resource
    private ApplicationContext applicationContext;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void addUserMoments(UserMoments userMoments) throws Exception {
        //1、发布动态
        Date now = new Date();
        userMoments.setCreateTime(now);
        userMoments.setUpdateTime(now);
        userMoments.setIsDelete(UserConstant.NORMAL_FLAG);
        userMomentsDao.addUserMoments(userMoments);
        //2、往RocketMQ中发送一条消息
        //通过applicationContext从IOC容器中获取之前定义的生产者
        DefaultMQProducer producer = (DefaultMQProducer)applicationContext.getBean("momentsProducer");
        //构建Message，注意必须是RocketMQ中消息
        Message message = new Message(UserMomentsConstant.TOPIC_MOMENTS, JSONObject.toJSONBytes(userMoments));
        //使用同步方式发送消息
        RocketMQUtil.syncSendMsg(producer, message);
    }

    @Override
    public List<UserMoments> getUserSubscribedMoments(Long userId) {
        String key = "subscribed-" + userId;
        String subscribedStr = redisTemplate.opsForValue().get(key);
        List<UserMoments> subscribedList = JSONArray.parseArray(subscribedStr, UserMoments.class);
        return subscribedList;
    }
}
